<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :before-show="true">
        <template #before>
          <span>共{{ page.total }}条记录</span>
        </template>
        <template v-slot:after>
          <el-button size="small" type="success" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" :disabled="!checkPermission('POINT-USER-ADD')" @click="dialogVisible = true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card>
        <el-table border :data="list">
          <template v-slot:empty>
            <span>加载中...</span>
          </template>
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column label="头像" sortable="" width="120px">
            <template v-slot="{row}">
              <img
                v-imageErr="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="display: block; width: 100px; height: 100px; border-radius: 50%;"
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column prop="formOfEmployment" label="聘用形式" :formatter="formOfEmployment" sortable="" />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template v-slot="{ row }">
              <el-switch
                :value="row.enableState === 1"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :total="page.total"
            :current-page="page.page"
            :page-size="page.size"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
    </div>
    <add-employee :dialog-visible.sync="dialogVisible" />
    <el-dialog title="二维码" :visible="qrcodeShow" @close="qrcodeShow = false">
      <el-row type="flex" justify="center">
        <canvas ref="qrcodeCanvas" />
      </el-row>
    </el-dialog>
    <AssignRole ref="assignRole" :show-dialog.sync="showDialog" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeesInfo, delEmployee } from '@/api/employess'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'

export default {
  name: 'Employees',
  components: {
    AddEmployee, AssignRole
  },
  data() {
    return {
      list: [], // 员工信息列表
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      dialogVisible: false, // 新增员工弹层
      qrcodeShow: false, // 二维码显示
      showDialog: false,
      userId: null
    }
  },
  watch: {
    list(newList, oldList) {
      if (newList.length < 1) {
        this.page.page--
        this.getEmployeesInfo()
      }
    }
  },
  created() {
    this.getEmployeesInfo()
  },
  methods: {
    // 获取员工信息列表
    async getEmployeesInfo() {
      const { total, rows } = await getEmployeesInfo(this.page)
      this.page.total = total
      this.list = rows
    },
    // 换页
    changePage(page) {
      this.page.page = page
      this.getEmployeesInfo()
    },
    // 转化员工的 聘用形式 信息
    formOfEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(obj => obj.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 删除员工
    async delEmployee(id) {
      try {
        await this.$confirm('确定删除此员工信息吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await delEmployee(id)
        this.$message.success('删除成功')
        this.getEmployeesInfo()
      } catch (err) {
        console.log(err)
      }
    },
    // 导出表单
    async exportExcel() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const tHeader = Object.keys(headers)
      const { rows } = await getEmployeesInfo({ page: 1, size: this.page.total })
      // console.log(rows)
      const data = this.formatJson(headers, rows)
      // console.log(data)
      // 复杂表头 生成需要的信息
      // 表头单元格信息
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      // 合并单元格的位置
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      // 懒加载生成excel表格的文件
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: tHeader, // 表头 必填
          data, // 具体数据 必填
          filename: '员工信息表', // 非必填
          multiHeader, // 复杂表头的部分
          merges // 需要合并的部分
        })
      })
    },
    // 将请求回来的数据转化为xlsx文件可用的格式
    formatJson(headers, rows) {
      return rows.map(item => {
        item.timeOfEntry = formatDate(item.timeOfEntry, 'yyyy/MM/dd')
        item.correctionTime = formatDate(item.correctionTime, 'yyyy/MM/dd')
        const obj = EmployeeEnum.hireType.find(obj => obj.id === item.formOfEmployment)
        item.formOfEmployment = obj ? obj.value : '未知'
        return [
          item.username,
          item.mobile,
          item.timeOfEntry,
          item.formOfEmployment,
          item.correctionTime,
          item.workNumber,
          item.departmentName
        ]
      })
    },
    showQrCode(url) {
      if (url) {
        this.qrcodeShow = true
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.qrcodeCanvas, url)
        })
      } else {
        this.$message.warning('暂无头像')
      }
    },
    async editRole(id) {
      this.userId = id
      await this.$refs.assignRole.getUserDetailById(id)
      this.showDialog = true
    }
  }
}
// {
//         // Object.keys拿到 映射关系的 对象的 key 的数组
//         return Object.keys(headers).map(val => {
//           // 时间数据需要格式化
//           if (headers[val] === 'timeOfEntry' || headers[val] === 'correctionTime') {
//             return formatDate(item[headers[val]], 'yyyy/MM/dd')
//           } else if (headers[val] === 'formOfEmployment') {
//             // 聘用形式的值是数字，将其格式化为中文
//             const obj = EmployeeEnum.hireType.find(obj => obj.id === item[headers[val]])
//             return obj ? obj.value : '未知'
//           }
//           // rows每一项中找出对应的值（根据headers的顺序）  map方法return回去一个数组
//           return item[headers[val]]
//         })
//       }
</script>

<style>
</style>
